package com.newlink.building.common_base.utils

import android.content.Context
import android.view.Gravity
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.newlink.building.common_base.R
import com.newlink.building.common_base.base.BaseApplication

/**
 * @Author: Jake
 * @Date: 2023/2/8
 * @Description: wrapper toast
 */
object ToastUtils : LifecycleObserver {

    var toast: Toast? = null

    fun showTextToastLong(msg: String) {
        showTextToast(BaseApplication.context, msg, Toast.LENGTH_LONG)
    }

    fun showTextToast(msg: String) {
        showTextToast(BaseApplication.context, msg)
    }

    fun showTextToast(context1: Context, msg: String) {
        if (toast != null) {
            toast?.cancel()
        }
        val context = BaseApplication.context
        showTextToast(context, msg, Toast.LENGTH_SHORT)
    }

    fun showTextToast(context: Context, msg: String, length: Int = Toast.LENGTH_SHORT) {
        if (toast != null) {
            toast?.cancel()
        }
        context.let {
            toast = Toast(it)
            val view = View.inflate(it, R.layout.toast_custom, null)
            val textView = view.findViewById<TextView>(R.id.tv_prompt)
            textView?.text = msg
            toast?.view = view
            toast?.duration = length
            toast?.setGravity(Gravity.CENTER, 0, 0)
            toast?.show()
        }
    }

    fun showTextToast(context: Context, @StringRes msg: Int) {
        showTextToast(context, context.resources.getString(msg))
    }

    fun cancel() {
        if (toast != null) {
            toast?.view = null
            toast?.cancel()
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    open fun onDestroy(owner: LifecycleOwner) {
        toast?.cancel()
        toast = null
        owner.lifecycle.removeObserver(this)
    }
}
